package framework.base;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.reflect.FieldUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import framework.utils.DateUtils;

public class BaseController {

	public static final String RESULT = "result";
	public static final String ERROR = "error";

	public static final String INFO = "info";

	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";
	
	protected ModelAndView infoModelAndView(String viewName, Object info)
	{
		ModelAndView view = new ModelAndView(viewName);
		view.addObject(INFO, info);

		return view;
	}
	
	protected ModelAndView indexModelAndView(String viewName)
	{
		ModelAndView view = new ModelAndView(viewName);

	/*	// 当前登录用户ID
		view.addObject("loginUserId", XUtils.getCurrentUser().getUserId());

		// 每页数据条数，此项为个性化设置，默认20
		view.addObject("pageSize", XUtils.getCurrentUser().getPageSize());

		// 页面每页数据条数列表，此项为系统全局设置
		view.addObject("pageList", XUtils.getPropertiesBean().getPageList());
*/
		return view;
	}
	
	public <T> T parseForm(Class<T> clazz, HttpServletRequest request) {
		T result = null;
		try {
			result = clazz.newInstance();
		} catch (Exception e) {

		}
		Field[] fieldArray = clazz.getDeclaredFields();
		Field[] superFieldArray = clazz.getSuperclass().getDeclaredFields();
		Field[] allFieldArray = (Field[]) ArrayUtils.addAll(fieldArray, superFieldArray);
		if (ArrayUtils.isEmpty(allFieldArray)) {
			return result;
		}

		fillFieldValue(result, superFieldArray, request);

		return result;

	}
	protected List parseForm(Class<? extends BaseEntity> clazz, List<Map> list)
	{
		List resultList = new ArrayList();

		if (CollectionUtils.isEmpty(list))
			return resultList;

		Field[] allFieldArray = clazz.getDeclaredFields();
		if (ArrayUtils.isEmpty(allFieldArray))
			return resultList;

		for (Map map : list)
		{
			Object object = null;

			try
			{
				object = clazz.newInstance();
			}
			catch (Exception ex)
			{
				return resultList;
			}

			fillFieldValue(object, allFieldArray, map);
			resultList.add(object);
		}

		return resultList;
	}


	private void fillFieldValue(Object entity, Field[] fieldArray, Object request) {
		if ((request instanceof HttpServletRequest) || (request instanceof Map)) {
			for (Field field : fieldArray) {

				String fieldName = field.getName();
				if (StringUtils.isNotEmpty(fieldName)) {
					int modifiers = field.getModifiers();
					if (Modifier.isFinal(modifiers) || Modifier.isStatic(modifiers)) {
						continue;
					}
					String value = null;
					if (request instanceof MultipartHttpServletRequest) {
						String[] array = ((MultipartHttpServletRequest) request).getParameterValues(fieldName);
						if (ArrayUtils.isNotEmpty(array)) {
							value = array[0];
						}
					} else if (request instanceof HttpServletRequest) {
						value = ((HttpServletRequest) request).getParameter(fieldName);
					} else {
						value = String.valueOf(((Map) request).get(fieldName));
					}

					if (StringUtils.isNotEmpty(value)) {
						Object obj = convertValue(field, value);
						if (obj != null) {
							try {
								FieldUtils.writeField(field, entity, obj,true);
							} catch (Exception e) {

							}
						}
					}
				}

			}

		}
	}

	private Object convertValue(Field field, String stringValue) {
		Class type = field.getType();
		try {
			Object value = null;
			if (type.equals(String.class)) {
				value = stringValue;
			} else if (type.equals(Long.class)) {
				value = Long.parseLong(stringValue);
			} else if (type.equals(Double.class)) {
				value = Double.parseDouble(stringValue);
			} else if (type.equals(Float.class)) {
				value = Float.parseFloat(stringValue);
			} else if (type.equals(Short.class)) {
				value = Short.parseShort(stringValue);
			} else if (type.equals(Byte.class)) {
				value = Byte.parseByte(stringValue);
			} else if (type.equals(Integer.class)) {
				value = Integer.parseInt(stringValue);
			} else if (type.equals(Byte.class)) {
				value = Byte.parseByte(stringValue);
			} else if (type.equals(java.util.Date.class)) {
				String newStringValue = stringValue.replaceAll("[^0-9]", "");
				if (StringUtils.length(newStringValue) == 6)
					value = DateUtils.parseDate(newStringValue, "yyyyMM");
				else if (StringUtils.length(newStringValue) == 8)
					value = DateUtils.parseDate(newStringValue, "yyyyMMdd");
				else if (StringUtils.length(newStringValue) == 10)
					value = DateUtils.parseDate(newStringValue, "yyyyMMddHH");
				else if (StringUtils.length(newStringValue) == 12)
					value = DateUtils.parseDate(newStringValue, "yyyyMMddHHmm");
				else if (StringUtils.length(newStringValue) == 14)
					value = DateUtils.parseDate(newStringValue, "yyyyMMddHHmmss");
				else
					value = DateUtils.parseDate(stringValue, new String[] { "yyyyMMdd", "yyyyMMddHHmmss" });
			} else {
				value = type.getConstructor(String.class).newInstance(stringValue);
			}
			return value;
		} catch (Exception e) {
			return null;
		}
	}

}
